import router from '@/router';
import { GET_TOKEN } from '@/utils/token';
import { useUserStore } from '@/stores/modules/userStore';
import { showFailToast } from 'vant';

router.beforeEach(async (to, from, next) => {
    const token = GET_TOKEN();
    const toPath = to.path;
    const userStore = useUserStore();
    const userType = localStorage.getItem('userType');
    document.title = to.meta.title || '标题';
    if (token) {
        if (toPath === '/login') {
            if (userType) {
                next({ path: `/${userType}` });
            } else {
                await userStore.login();
                next();
            }
        } else {
            // 如果有hasData,正常跳转,没有的话代表用户信息丢失,需要重新获取用户信息
            if (userStore.hasData) {
                // 限制用户所跳转的页面,如果userType='teacher',那么只能跳转开头以teacher的路由
                if (toPath.startsWith(`/${userType}`) || toPath === '/404') {
                    next();
                } else {
                    next({ path: `/${userType}` });
                }
            } else {
                try {
                    await userStore.login('');
                    next();
                } catch (e) {
                    showFailToast(e.message || '获取用户信息失败');
                    userStore.logout();
                }
            }
        }
    } else {
        if (to.meta.isRequired === false) {
            next();
        } else {
            next({ path: '/login', query: { redirect: to.name } });
        }
    }
});
